document.addEventListener('DOMContentLoaded', function() {
    const createTableForm = document.getElementById('createTableForm');
    const addFieldBtn = document.getElementById('addFieldBtn');
    const fieldsContainer = document.getElementById('fieldsContainer');
    // 移除与操作类型和执行操作按钮相关的所有JS逻辑
    // 不再获取operationType、executeOperationBtn，不再绑定相关事件，不再包含相关操作函数
    // 只保留表格选择、字段设置和表格渲染功能
    const executeOperationBtn = document.getElementById('executeOperationBtn');
    const selectTable = document.getElementById('selectTable');
    const operationType = document.getElementById('operationType');
    const operationResult = document.getElementById('operationResult');
    const resultContent = document.getElementById('resultContent');
    
    // 初始化页面
    const tablesList = document.getElementById('tablesList');
    loadTablesList();
    window.loadTablesList = loadTablesList;
    
    // 添加字段按钮
    if (addFieldBtn) {
    addFieldBtn.addEventListener('click', function() {
        addFieldRow();
    });
    }
    
    // 字段名校验（只要非空且不重复即可）
    // const fieldNamePattern = /^[\u4e00-\u9fa5a-zA-Z_][\u4e00-\u9fa5a-zA-Z0-9_]*$/;
    // select类型字段弹窗输入选项
    function addFieldRow() {
        const fieldRow = document.createElement('div');
        fieldRow.className = 'field-row';
        fieldRow.innerHTML = `
            <input type="text" placeholder="字段名称" class="field-name">
            <select class="field-type">
                <option value="text">文本</option>
                <option value="number">数字</option>
                <option value="date">日期</option>
                <option value="select">选择</option>
                <option value="textarea">多行文本</option>
            </select>
            <input type="text" placeholder="约束条件" class="field-constraint">
            <button type="button" class="btn btn-info btn-sm set-options" style="display:none;margin-right:8px;">设置选项</button>
            <button type="button" class="btn btn-danger btn-sm remove-field">删除</button>
        `;
        if (fieldsContainer) {
        fieldsContainer.appendChild(fieldRow);
        }
        // 绑定删除按钮事件
        if (fieldRow) {
        fieldRow.querySelector('.remove-field').addEventListener('click', function() {
                if (fieldsContainer && fieldsContainer.children.length > 1) {
                fieldRow.remove();
            } else {
                showCenterModal('至少需要保留一个字段！');
            }
        });
        }
        // 绑定select类型显示设置选项按钮
        if (fieldRow) {
        const typeSelect = fieldRow.querySelector('.field-type');
        const setOptionsBtn = fieldRow.querySelector('.set-options');
            if (typeSelect) {
        typeSelect.addEventListener('change', function() {
            if (this.value === 'select') {
                        if (setOptionsBtn) setOptionsBtn.style.display = '';
            } else {
                        if (setOptionsBtn) setOptionsBtn.style.display = 'none';
                        if (fieldRow) fieldRow.removeAttribute('data-options');
                    }
                });
            }
        }
        // 设置选项弹窗
        if (fieldRow) {
            const setOptionsBtn = fieldRow.querySelector('.set-options');
            if (setOptionsBtn) {
        setOptionsBtn.addEventListener('click', function() {
            let options = fieldRow.getAttribute('data-options') || '';
            options = prompt('请输入下拉选项（用逗号分隔）：', options);
            if (options !== null) {
                fieldRow.setAttribute('data-options', options);
            }
        });
            }
        }
    }
    // 初始字段行也加上设置选项按钮逻辑
    (function bindInitFieldRow() {
        const row = fieldsContainer ? fieldsContainer.querySelector('.field-row') : null;
        if (!row) return;
        const typeSelect = row.querySelector('.field-type');
        const setOptionsBtn = document.createElement('button');
        setOptionsBtn.type = 'button';
        setOptionsBtn.className = 'btn btn-info btn-sm set-options';
        setOptionsBtn.style.display = 'none';
        setOptionsBtn.style.marginRight = '8px';
        setOptionsBtn.textContent = '设置选项';
        if (typeSelect) {
        typeSelect.after(setOptionsBtn);
        typeSelect.addEventListener('change', function() {
            if (this.value === 'select') {
                    if (setOptionsBtn) setOptionsBtn.style.display = '';
            } else {
                    if (setOptionsBtn) setOptionsBtn.style.display = 'none';
                    if (row) row.removeAttribute('data-options');
            }
        });
        setOptionsBtn.addEventListener('click', function() {
            let options = row.getAttribute('data-options') || '';
            options = prompt('请输入下拉选项（用逗号分隔）：', options);
            if (options !== null) {
                row.setAttribute('data-options', options);
            }
        });
        }
    })();
    // 创建表格表单提交
    if (createTableForm) {
    createTableForm.addEventListener('submit', function(e) {
        e.preventDefault();
        // 表格名唯一性校验（前端）
            const tableName = document.getElementById('tableName');
            if (!tableName || !tableName.value) {
            showCenterModal('请输入表格名称！');
            return;
        }
            const tableNameValue = tableName.value.trim();
        const allTableNames = Array.from(document.querySelectorAll('.table-card h4')).map(h => h.textContent.trim());
            if (allTableNames.includes(tableNameValue)) {
            showCenterModal('表格名称已存在，请更换！');
            return;
        }
        // 收集字段信息
        const fields = [];
            const fieldRows = fieldsContainer ? fieldsContainer.querySelectorAll('.field-row') : [];
        const fieldNamesSet = new Set();
        let hasError = false;
        fieldRows.forEach(row => {
                const fieldName = row.querySelector('.field-name');
                const fieldType = row.querySelector('.field-type');
                const fieldConstraint = row.querySelector('.field-constraint');
            let options = row.getAttribute('data-options') || '';
                if (!fieldName || !fieldName.value) {
                showCenterModal('字段名称不能为空！');
                hasError = true;
                return;
            }
            // if (!fieldNamePattern.test(fieldName)) {
            //     alert('字段名只能包含中文、字母、数字、下划线，且不能以数字开头！');
            //     hasError = true;
            //     return;
            // }
                if (fieldNamesSet.has(fieldName.value)) {
                showCenterModal('字段名不能重复！');
                hasError = true;
                return;
            }
                if (!fieldType || !fieldType.value) {
                showCenterModal('请选择字段类型！');
                hasError = true;
                return;
            }
                fieldNamesSet.add(fieldName.value);
            const fieldObj = {
                    name: fieldName.value,
                    type: fieldType.value,
                    constraint: fieldConstraint ? fieldConstraint.value.trim() : ''
                };
                if (fieldType.value === 'select') {
                if (!options.trim()) {
                    showCenterModal('select类型字段必须设置选项！');
                    hasError = true;
                    return;
                }
                fieldObj.options = options.split(',').map(s => s.trim()).filter(Boolean);
            }
            fields.push(fieldObj);
        });
        if (hasError) return;
        if (fields.length === 0) {
            showCenterModal('请至少添加一个字段！');
            return;
        }
        // POST到后端
        fetch('http://localhost:3000/api/custom-tables', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': sessionStorage.getItem('token') || ''
            },
            body: JSON.stringify({
                    name: tableNameValue,
                    description: document.getElementById('tableDescription') ? document.getElementById('tableDescription').value.trim() : '',
                fields: fields
            })
        })
        .then(res => res.json())
        .then(data => {
            if (data.message === '创建成功') {
                showCenterModal('表格创建成功！');
                createTableForm.reset();
                    if (fieldsContainer) {
                fieldsContainer.innerHTML = `
                    <div class="field-row">
                        <input type="text" placeholder="字段名称" class="field-name">
                        <select class="field-type">
                            <option value="text">文本</option>
                            <option value="number">数字</option>
                            <option value="date">日期</option>
                            <option value="select">选择</option>
                            <option value="textarea">多行文本</option>
                        </select>
                        <input type="text" placeholder="约束条件" class="field-constraint">
                        <button type="button" class="btn btn-danger btn-sm remove-field">删除</button>
                    </div>
                `;
                    }
                    // loadTablesList(); // This line is removed as per the edit hint
                if (typeof createTableModal !== 'undefined') {
                    createTableModal.style.display = 'none';
                } else {
                    const modal = document.getElementById('createTableModal');
                    if (modal) modal.style.display = 'none';
                }
                loadTablesList(); // 刷新表格列表
            } else {
                showCenterModal(data.error || '创建失败');
            }
        })
        .catch(() => {
            showCenterModal('创建表格失败，您可能没有权限或服务器异常');
        });
    });
    }
    
    // 执行操作按钮
    if (executeOperationBtn) {
    executeOperationBtn.addEventListener('click', function() {
        executeTableOperation();
    });
    }
    
    // 新建表格弹窗逻辑
    const openCreateTableModalBtn = document.getElementById('openCreateTableModal');
    const createTableModal = document.getElementById('createTableModal');
    const closeCreateTableModalBtn = document.getElementById('closeCreateTableModal');
    if (openCreateTableModalBtn && createTableModal && closeCreateTableModalBtn) {
        openCreateTableModalBtn.onclick = function() {
            createTableModal.style.display = 'flex';
        };
        closeCreateTableModalBtn.onclick = function() {
            createTableModal.style.display = 'none';
        };
        createTableModal.onclick = function(e) {
            if (e.target === createTableModal) createTableModal.style.display = 'none';
        };
    }
    
    // 覆盖 loadTablesList，展示系统表+后端自定义表
    function loadTablesList() {
        let html = '<div class="tables-grid">';
        // 只显示自定义表格
        fetch('http://localhost:3000/api/custom-tables', {
            headers: { 'Authorization': sessionStorage.getItem('token') || '' }
        })
        .then(res => res.json())
        .then(tables => {
            tables.forEach(table => {
                let fieldCount = 0;
                let safeFields = [];
                if (Array.isArray(table.fields)) {
                    safeFields = table.fields.filter(f => f && f.name);
                    fieldCount = safeFields.length;
                } else if (typeof table.fields === 'object' && table.fields) {
                    safeFields = Object.keys(table.fields).map(k => ({ name: k }));
                    fieldCount = safeFields.length;
                }
                html += `
                    <div class="table-card">
                        <h4>${table.name}</h4>
                        <p>${table.description || '自定义表格'}</p>
                        <div class="table-actions">
                            <button class="btn btn-success btn-sm" onclick="viewCustomTable(${table.id});event.stopPropagation();">查看</button>
                            <button class="btn btn-primary btn-sm" onclick="enterCustomTable(${table.id});event.stopPropagation();">编辑</button>
                            <button class="btn btn-secondary btn-sm" onclick="customTableBackup(${table.id}, '${table.name}');event.stopPropagation();">备份</button>
                            <button class="btn btn-danger btn-sm" onclick="deleteCustomTable(event, ${table.id})">删除</button>
                        </div>
                    </div>
                `;
            });
            html += '</div>';
            if (tablesList) tablesList.innerHTML = html;
        })
        .catch(() => {
            html += '</div>';
            if (tablesList) tablesList.innerHTML = html;
        });
    }
    window.loadTablesList = loadTablesList;
    
    // 自定义表格Excel导出（确保全局）
    window.customTableBackup = function(tableId, tableName) {
      const defaultName = `${tableName}_backup_${new Date().toISOString().split('T')[0]}`;
      showCenterPrompt('请输入导出文件名（无需后缀）', defaultName, function(filename) {
        if (!filename) return;
        fetch(`/api/custom-tables/${tableId}/export?filename=${encodeURIComponent(filename)}.xlsx`, {
          headers: { 'Authorization': sessionStorage.getItem('token') || '' }
        })
          .then(res => {
            if (!res.ok) throw new Error('导出失败');
            return res.blob();
          })
          .then(blob => {
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `${filename}.xlsx`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
          })
          .catch(() => showCenterModal('导出失败'));
      });
    };
    
    // 查看自定义表格弹窗逻辑
    window.viewCustomTable = async function(tableId) {
        const modal = document.getElementById('viewTableModal');
        const content = document.getElementById('viewTableModalContent');
        content.innerHTML = '<div style="padding:32px;text-align:center;">加载中...</div>';
        modal.style.display = 'flex';
        try {
            // 获取表结构
            const res1 = await fetch(`http://localhost:3000/api/custom-tables/${tableId}`, {
                headers: { 'Authorization': sessionStorage.getItem('token') || '' }
            });
            const table = await res1.json();
            // 获取表数据
            const res2 = await fetch(`http://localhost:3000/api/custom-tables/${tableId}/data`, {
                headers: { 'Authorization': sessionStorage.getItem('token') || '' }
            });
            const rows = await res2.json();
            // 渲染表格
            let html = `<h3 style='margin-bottom:18px;'>${table.name} <span style='font-size:0.7em;color:#888;'>${table.description||''}</span></h3>`;
            if (!Array.isArray(table.fields) || table.fields.length === 0) {
                html += '<div style="color:#888;">无字段定义</div>';
            } else {
                html += '<div style="overflow-x:auto;"><table class="custom-table-data" style="min-width:600px;max-width:100%;margin-bottom:12px;">';
                html += '<thead><tr>';
                table.fields.forEach(f => {
                    html += `<th>${f.name}</th>`;
                });
                html += '</tr></thead><tbody>';
                if (rows.length === 0) {
                    html += `<tr><td colspan="${table.fields.length}" style="color:#aaa;text-align:center;">暂无数据</td></tr>`;
                } else {
                    rows.forEach(row => {
                        html += '<tr>';
                        table.fields.forEach(f => {
                            html += `<td>${row.data && row.data[f.name] !== undefined ? row.data[f.name] : ''}</td>`;
                        });
                        html += '</tr>';
                    });
                }
                html += '</tbody></table></div>';
            }
            html += '<div style="text-align:right;"><button class="btn btn-secondary" id="closeViewTableModalBtn">关闭</button></div>';
            content.innerHTML = html;
            document.getElementById('closeViewTableModalBtn').onclick = function() {
                modal.style.display = 'none';
            };
            // 点击弹窗外部关闭
            modal.onclick = function(e) {
                if (e.target === modal) modal.style.display = 'none';
            };
        } catch (e) {
            content.innerHTML = '<div style="color:red;padding:32px;">加载失败</div>';
        }
    };
    
    // 新增：异步从后端接口拉取表格数据
    async function fetchTableData(tableName) {
        let url = '';
        if (tableName === 'foods') url = 'http://localhost:3000/api/foods';
        else if (tableName === 'ingredients') url = 'http://localhost:3000/api/ingredients';
        else if (tableName === 'products') url = 'http://localhost:3000/api/products';
        else return [];
        try {
            const res = await fetch(url, { headers: { 'Authorization': sessionStorage.getItem('token') || '' } });
            if (!res.ok) return [];
            return await res.json();
        } catch (e) {
            return [];
        }
    }

    // 全局定义：获取当前表的全部字段和中文名
    function getTableFieldConfig(tableName) {
        if (tableName === 'foods') {
            return {
                showFields: ['photo', 'name', 'origin', 'production_date', 'producer', 'season', 'description'],
                fieldNameMap: {
                    photo: '照片',
                    name: '食物名称',
                    origin: '产地',
                    production_date: '出产日期',
                    producer: '生产单位/农户',
                    season: '出产季节',
                    description: '描述'
                }
            };
        } else if (tableName === 'ingredients') {
            return {
                showFields: ['photo', 'name', 'category', 'origin', 'production_date', 'producer', 'price', 'supplier', 'description'],
                fieldNameMap: {
                    photo: '照片',
                    name: '食材名称',
                    category: '食材分类',
                    origin: '产地',
                    production_date: '出产日期',
                    producer: '生产单位',
                    price: '交易价格',
                    supplier: '供货商',
                    description: '介绍'
                }
            };
        } else if (tableName === 'products') {
            return {
                showFields: ['photo', 'name', 'origin', 'production_date', 'producer', 'price', 'supplier', 'main_ingredient', 'description', 'method', 'effect', 'relation'],
                fieldNameMap: {
                    photo: '照片',
                    name: '食品名称',
                    origin: '产地',
                    production_date: '出产日期',
                    producer: '生产单位',
                    price: '交易价格',
                    supplier: '供货商',
                    main_ingredient: '主要成分',
                    description: '介绍',
                    method: '制作方法',
                    effect: '功效',
                    relation: '关联食谱'
                }
            };
        }
        return { showFields: [], fieldNameMap: {} };
    }

    // 全局定义：获取/保存字段设置到localStorage
    function getUserFieldSetting(tableName) {
        const key = 'fieldSetting_' + tableName;
        const val = localStorage.getItem(key);
        if (val) {
            try { return JSON.parse(val); } catch { return null; }
        }
        return null;
    }
    function setUserFieldSetting(tableName, arr) {
        const key = 'fieldSetting_' + tableName;
        localStorage.setItem(key, JSON.stringify(arr));
    }

    // 字段设置弹窗逻辑
    if (fieldSettingBtn) {
        fieldSettingBtn.addEventListener('click', function() {
            const tableName = selectTable ? selectTable.value : '';
            if (!tableName) {
                showCenterModal('请先选择表格');
                return;
            }
            const { showFields, fieldNameMap } = getTableFieldConfig(tableName);
            let userSetting = getUserFieldSetting(tableName);
            if (!userSetting) userSetting = showFields.map(f => ({ field: f, checked: true }));
            // 渲染复选框
            if (fieldSettingList) {
                fieldSettingList.innerHTML = userSetting.map((item, idx) =>
                    `<div style="display:flex;align-items:center;margin-bottom:6px;">
                        <input type="checkbox" id="field_ck_${idx}" data-field="${item.field}" ${item.checked ? 'checked' : ''}>
                        <label for="field_ck_${idx}" style="margin-left:8px;">${fieldNameMap[item.field] || item.field}</label>
                    </div>`
                ).join('');
            }
            if (fieldSettingModal) fieldSettingModal.style.display = 'flex';
        });
    }
    // 关闭弹窗
    if (cancelFieldSettingBtn) {
        cancelFieldSettingBtn.addEventListener('click', function() {
            if (fieldSettingModal) fieldSettingModal.style.display = 'none';
        });
    }
    // 保存设置
    if (saveFieldSettingBtn) {
        saveFieldSettingBtn.addEventListener('click', function() {
            const tableName = selectTable ? selectTable.value : '';
            const { showFields } = getTableFieldConfig(tableName);
            const arr = [];
            if (fieldSettingList) {
                fieldSettingList.querySelectorAll('input[type=checkbox]').forEach((ck, idx) => {
                    arr.push({ field: showFields[idx], checked: ck.checked });
                });
            }
            setUserFieldSetting(tableName, arr);
            if (fieldSettingModal) fieldSettingModal.style.display = 'none';
            // 刷新表格
            refreshTableData(tableName);
        });
    }

    // 新增：表格数据渲染函数支持异步数据
    function renderTableData(tableName, data, highlightMap) {
        const container = document.getElementById('tableDataContainer');
        const operationBar = document.getElementById('tableOperationBar');
        if (!data || data.length === 0) {
            container.innerHTML = '<div style="color:#888;text-align:center;padding:18px 0;">无匹配数据</div>';
            if (operationBar) operationBar.style.display = 'none';
            return;
        }
        if (operationBar) operationBar.style.display = '';
        const { showFields, fieldNameMap } = getTableFieldConfig(tableName);
        let userSetting = getUserFieldSetting(tableName);
        let fieldsToShow = showFields;
        if (userSetting) {
            fieldsToShow = userSetting.filter(x => x.checked).map(x => x.field);
        }
        let html = '<table class="custom-table-data"><thead><tr>';
        // 移除表头全选checkbox
        // html += '<th><input type="checkbox" id="selectAllRows"></th>';
        html += '<th></th>';
        fieldsToShow.forEach(f => {
            html += `<th>${fieldNameMap[f]}</th>`;
        });
        html += '</tr></thead><tbody>';
        data.forEach((row, idx) => {
            html += `<tr>`;
            html += `<td><input type="checkbox" class="rowCheckbox" data-row-idx="${idx}"></td>`;
            fieldsToShow.forEach(f => {
                let cellValue = row[f] !== undefined ? row[f] : '';
                if (f === 'photo' && cellValue) {
                    cellValue = `<img src="http://localhost:3000/uploads/${cellValue}" alt="图片" style="max-width:80px;max-height:80px;border-radius:6px;">`;
                } else if (cellValue && highlightMap) {
                    let highlightVal = highlightMap[f];
                    if (highlightVal) {
                        const reg = new RegExp(`(${highlightVal.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
                        cellValue = String(cellValue).replace(reg, '<span class="highlight">$1</span>');
                    }
                    if (highlightMap['*']) {
                        const reg2 = new RegExp(`(${highlightMap['*'].replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
                        cellValue = String(cellValue).replace(reg2, '<span class="highlight">$1</span>');
                    }
                }
                html += `<td>${cellValue}</td>`;
            });
            html += '</tr>';
        });
        html += '</tbody></table>';
        if (container) container.innerHTML = html;
        // 操作按钮区显示
        // if (operationBar) operationBar.style.display = ''; // This line is removed as per the edit hint
        // 绑定全选
        const selectAll = document.getElementById('selectAllRows');
        const checkboxes = container.querySelectorAll('.rowCheckbox');
        if (selectAll) {
            selectAll.onclick = function() {
                checkboxes.forEach(cb => { cb.checked = selectAll.checked; });
                updateOperationBtns();
            };
        }
        checkboxes.forEach(cb => {
            cb.onclick = updateOperationBtns;
        });
        updateOperationBtns();
        updateSelectAllBtn(); // 每次渲染表格后自动更新全选按钮文案
    }
    // 操作按钮区逻辑 - 不再依赖选中状态
    function updateOperationBtns() {
        // 改为空函数，不再控制按钮显示/隐藏
        // 按钮区显示/隐藏完全由表格数据控制
    }
    // 备份（导出Excel）
    document.getElementById('backupSelectedBtn')?.addEventListener('click', async function() {
        const container = document.getElementById('tableDataContainer');
        const checkboxes = container ? container.querySelectorAll('.rowCheckbox') : [];
        const tableName = selectTable ? selectTable.value : '';
        if (!tableName) return;
        // 获取所有选中行
        const selectedIdx = Array.from(checkboxes).map((cb, i) => cb.checked ? i : -1).filter(i => i !== -1);
        if (selectedIdx.length === 0) {
            showCenterModal('请先选择要备份的数据');
            return;
        }
        const ids = selectedIdx.map(i => currentTableData[i].id);
        // 弹窗输入文件名
        const defaultName = `${tableName}_selected_${new Date().toISOString().split('T')[0]}`;
        showCenterPrompt('请输入导出文件名（无需后缀）', defaultName, async function(filename) {
            if (!filename) return;
            // 请求后端批量导出接口
            const res = await fetch(`/api/backup/${tableName}/selected?filename=${encodeURIComponent(filename)}.xlsx`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': sessionStorage.getItem('token') || ''
                },
                body: JSON.stringify({ ids })
            });
            if (!res.ok) {
                showCenterModal('导出失败');
                return;
            }
            const blob = await res.blob();
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `${filename}.xlsx`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
        });
    });
    // 删除选中 - 如果没有选中行，提示必须选择
    document.getElementById('deleteSelectedBtn')?.addEventListener('click', async function() {
        const container = document.getElementById('tableDataContainer');
        const checkboxes = container ? container.querySelectorAll('.rowCheckbox') : [];
        const tableName = selectTable ? selectTable.value : '';
        if (!tableName) return;
        
        const selectedIdx = Array.from(checkboxes).map((cb, i) => cb.checked ? i : -1).filter(i => i !== -1);
        if (selectedIdx.length === 0) {
            showCenterModal('请先选择要删除的数据');
            return;
        }
        
        showCenterConfirm('确定要删除选中的数据吗？', async function(ok) {
            if (ok) {
                const ids = selectedIdx.map(i => currentTableData[i].id);
                // 调用后端批量删除接口
                const res = await fetch(`/api/${tableName}/batch-delete`, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': sessionStorage.getItem('token') || ''
                    },
                    body: JSON.stringify({ ids })
                });
                if (!res.ok) {
                    showCenterModal('删除失败');
                    return;
                }
                // 删除成功后刷新表格数据
                const data = await fetchTableData(tableName);
                currentTableData = data;
                renderTableData(tableName, data);
                // 绿色主题提示弹窗
                showSuccessToast('删除成功！');
            }
        });
    });
    // 导出Excel工具函数
    function exportToExcel(rows, tableName) {
        if (!rows || rows.length === 0) return;
        const { showFields, fieldNameMap } = getTableFieldConfig(tableName);
        let userSetting = getUserFieldSetting(tableName);
        let fieldsToShow = showFields;
        if (userSetting) {
            fieldsToShow = userSetting.filter(x => x.checked).map(x => x.field);
        }
        let csv = fieldsToShow.map(f => `"${fieldNameMap[f]}"`).join(',') + '\n';
        rows.forEach(row => {
            csv += fieldsToShow.map(f => `"${row[f] !== undefined ? String(row[f]).replace(/"/g, '""') : ''}"`).join(',') + '\n';
        });
        const blob = new Blob([csv], { type: 'text/csv' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `${tableName}_export_${new Date().toISOString().split('T')[0]}.csv`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }

    let currentTableData = [];

    // 修改：选择表格后异步加载数据
    const tableSearchInput = document.getElementById('tableSearchInput');
    if (selectTable) {
        selectTable.addEventListener('change', async function() {
            if (fieldSettingBtn) {
                fieldSettingBtn.style.display = this.value ? '' : 'none';
            }
            if (tableSearchInput) {
                tableSearchInput.style.display = this.value ? '' : 'none';
            }
            const tableName = this.value;
            const operationBar = document.getElementById('tableOperationBar');
            if (tableName) {
                const data = await fetchTableData(tableName);
                currentTableData = data; // 保存原始数据
                renderTableData(tableName, data);
            } else {
                currentTableData = [];
                const container = document.getElementById('tableDataContainer');
                if (container) container.innerHTML = '';
                if (operationBar) operationBar.style.display = 'none';
            }
        });
    }

    // 搜索输入监听（多条件+高亮）
    if (tableSearchInput) {
        tableSearchInput.addEventListener('input', function() {
            const input = this.value.trim();
            const tableName = selectTable ? selectTable.value : '';
            if (!tableName) return;
            let filtered = currentTableData;
            let highlightMap = {};
            if (input) {
                // 解析多条件：字段:值
                const conds = [];
                const regex = /([\u4e00-\u9fa5a-zA-Z_]+):([^\s]+)/g;
                let m;
                let used = '';
                while ((m = regex.exec(input)) !== null) {
                    conds.push({ field: m[1], value: m[2] });
                    used += m[0];
                }
                const rest = input.replace(used, '').trim();
                // 字段映射
                const { showFields, fieldNameMap } = getTableFieldConfig(tableName);
                const fieldMap = {};
                Object.entries(fieldNameMap).forEach(([k, v]) => {
                    fieldMap[k] = v;
                    fieldMap[v] = k;
                });
                // 多条件过滤
                if (conds.length > 0) {
                    filtered = filtered.filter(row =>
                        conds.every(cond => {
                            // 支持中英文字段
                            let key = cond.field;
                            if (fieldMap[key]) key = fieldMap[key];
                            const val = row[key];
                            if (val == null) return false;
                            return String(val).toLowerCase().includes(cond.value.toLowerCase());
                        })
                    );
                    // 高亮map
                    conds.forEach(cond => {
                        let key = cond.field;
                        if (fieldMap[key]) key = fieldMap[key];
                        highlightMap[key] = cond.value;
                    });
                }
                // 剩余部分全字段模糊
                if (rest) {
                    filtered = filtered.filter(row =>
                        Object.values(row).some(val =>
                            val && String(val).toLowerCase().includes(rest.toLowerCase())
                        )
                    );
                    highlightMap['*'] = rest;
                }
            }
            renderTableData(tableName, filtered, highlightMap);
        });
    }

    // 操作类型切换时动态显示输入框（保持不变）
    if (operationType) {
        operationType.addEventListener('change', function() {
            const op = this.value;
            const inputContainer = document.getElementById('rowColInputContainer');
            const input = document.getElementById('rowColInput');
            const label = document.getElementById('rowColInputLabel');
            if (inputContainer && input && label) {
                if (op === 'deleteRows') {
                    inputContainer.style.display = '';
                    label.textContent = '请输入要删除的行号（如1,2,3或1-3）：';
                    input.placeholder = '如：1,2,3 或 1-3';
                } else if (op === 'deleteColumns') {
                    inputContainer.style.display = '';
                    label.textContent = '请输入要删除的列名（如name,price）：';
                    input.placeholder = '如：name,price';
                } else {
                    inputContainer.style.display = 'none';
                    input.value = '';
                }
            }
        });
    }

    // 修改：执行操作逻辑为异步，操作后刷新表格
    async function executeTableOperation() {
        const selectedTable = selectTable ? selectTable.value : '';
        const operation = operationType ? operationType.value : '';
        const input = document.getElementById('rowColInput') ? document.getElementById('rowColInput').value.trim() : '';
        if (!selectedTable) {
            showCenterModal('请选择表格！');
            return;
        }
        if (!operation) {
            showCenterModal('请选择操作类型！');
            return;
        }
        switch (operation) {
            case 'backup':
                backupTable(selectedTable);
                break;
            case 'deleteTable':
                showCenterConfirm('确定要删除整个表格吗？此操作不可恢复！', async function(ok) {
                    if (ok) {
                        await deleteTable(selectedTable);
                        await refreshTableData(selectedTable);
                    }
                });
                break;
            case 'deleteRows':
                if (!input) { showCenterModal('请输入要删除的行号！'); return; }
                await deleteTableRows(selectedTable, input);
                await refreshTableData(selectedTable);
                break;
            case 'deleteColumns':
                if (!input) { showCenterModal('请输入要删除的列名！'); return; }
                await deleteTableColumns(selectedTable, input);
                await refreshTableData(selectedTable);
                break;
        }
    }
    if (executeOperationBtn) {
        executeOperationBtn.addEventListener('click', executeTableOperation);
    }

    // 修改：删除/清空/列操作全部通过接口（这里只做示例，具体接口需后端支持）
    async function deleteTable(tableName) {
        // 假设有 DELETE /api/foods, /api/ingredients, /api/products
        let url = '';
        if (tableName === 'foods') url = 'http://localhost:3000/api/foods';
        else if (tableName === 'ingredients') url = 'http://localhost:3000/api/ingredients';
        else if (tableName === 'products') url = 'http://localhost:3000/api/products';
        else return;
        await fetch(url, { method: 'DELETE', headers: { 'Authorization': sessionStorage.getItem('token') || '' } });
        showResult(`表格 ${tableName} 已清空！`);
    }
    async function deleteTableRows(tableName, rowInput) {
        // 这里只做示例，实际应有后端接口支持批量删除
        // 假设有 DELETE /api/foods/row/1,2,3
        let url = '';
        if (tableName === 'foods') url = 'http://localhost:3000/api/foods/rows/' + encodeURIComponent(rowInput);
        else if (tableName === 'ingredients') url = 'http://localhost:3000/api/ingredients/rows/' + encodeURIComponent(rowInput);
        else if (tableName === 'products') url = 'http://localhost:3000/api/products/rows/' + encodeURIComponent(rowInput);
        else return;
        await fetch(url, { method: 'DELETE', headers: { 'Authorization': sessionStorage.getItem('token') || '' } });
        showResult(`已删除指定行！`);
    }
    async function deleteTableColumns(tableName, colInput) {
        // 这里只做示例，实际应有后端接口支持批量删除列
        // 假设有 DELETE /api/foods/columns/name,price
        let url = '';
        if (tableName === 'foods') url = 'http://localhost:3000/api/foods/columns/' + encodeURIComponent(colInput);
        else if (tableName === 'ingredients') url = 'http://localhost:3000/api/ingredients/columns/' + encodeURIComponent(colInput);
        else if (tableName === 'products') url = 'http://localhost:3000/api/products/columns/' + encodeURIComponent(colInput);
        else return;
        await fetch(url, { method: 'DELETE', headers: { 'Authorization': sessionStorage.getItem('token') || '' } });
        showResult(`已删除指定列！`);
    }
    
    function backupTable(tableName) {
        // 模拟备份操作
        const backupData = {
            tableName: tableName,
            backupTime: new Date().toISOString(),
            data: getTableData(tableName)
        };
        
        // 创建下载链接
        const dataStr = JSON.stringify(backupData, null, 2);
        const dataBlob = new Blob([dataStr], {type: 'application/json'});
        const url = URL.createObjectURL(dataBlob);
        
        const link = document.createElement('a');
        link.href = url;
        link.download = `${tableName}_backup_${new Date().toISOString().split('T')[0]}.json`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        showResult(`表格 ${tableName} 备份成功！`);
    }
    
    // 覆盖原有的deleteTableRows和deleteTableColumns，支持参数
    // function deleteTableRows(tableName, rowInput) {
    //     // 支持1,2,3和1-3格式
    //     const data = getTableData(tableName);
    //     let indexes = [];
    //     if (rowInput.includes('-')) {
    //         const [start, end] = rowInput.split('-').map(Number);
    //         for (let i = start; i <= end; i++) indexes.push(i-1);
    //     } else {
    //         indexes = rowInput.split(',').map(x => Number(x)-1);
    //     }
    //     // 从最新开始，倒序删除
    //     indexes = indexes.filter(i => i >= 0 && i < data.length).sort((a,b) => b-a);
    //     indexes.forEach(i => { data.splice(i, 1); });
    //     saveTableData(tableName, data);
    //     showResult(`已删除指定行！`);
    // }
    // function deleteTableColumns(tableName, colInput) {
    //     const cols = colInput.split(',').map(x => x.trim()).filter(Boolean);
    //     const data = getTableData(tableName);
    //     data.forEach(row => { cols.forEach(col => { delete row[col]; }); });
    //     saveTableData(tableName, data);
    //     showResult(`已删除指定列！`);
    // }
    
    function showResult(message) {
        if (resultContent) {
        resultContent.innerHTML = message;
        }
        if (operationResult) {
        operationResult.style.display = 'block';
        
        setTimeout(() => {
            operationResult.style.display = 'none';
        }, 3000);
        }
    }
    
    // 绑定初始删除按钮事件
    if (fieldsContainer) {
        fieldsContainer.querySelector('.remove-field').addEventListener('click', function() {
        if (fieldsContainer.children.length > 1) {
            this.closest('.field-row').remove();
        } else {
            showCenterModal('至少需要保留一个字段！');
        }
    });
    }

    // 编辑选中数据弹窗
    const editSelectedBtn = document.getElementById('editSelectedBtn');
    if (editSelectedBtn) {
        editSelectedBtn.addEventListener('click', async function() {
            const container = document.getElementById('tableDataContainer');
            const checkboxes = container ? container.querySelectorAll('.rowCheckbox') : [];
            const tableName = selectTable ? selectTable.value : '';
            if (!tableName) return;
            // 获取所有选中行
            const selectedIdx = Array.from(checkboxes).map((cb, i) => cb.checked ? i : -1).filter(i => i !== -1);
            if (selectedIdx.length !== 1) {
                showCenterModal('请只选择一条要编辑的数据');
                return;
            }
            const rowData = currentTableData[selectedIdx[0]];
            showEditDataModal(tableName, rowData);
        });
    }

    // 日期格式化工具
    function formatDateInput(val) {
      if (!val) return '';
      if (val.length === 10 && /^\d{4}-\d{2}-\d{2}$/.test(val)) return val;
      const d = new Date(val);
      if (isNaN(d)) return '';
      return d.toISOString().slice(0, 10);
    }

    // 表单字段配置，与添加页面保持一致
    const formFieldConfig = {
      foods: [
        { name: 'photo', label: '图片', type: 'photo' },
        { name: 'name', label: '名称', type: 'text', required: true },
        { name: 'origin', label: '产地', type: 'text', required: true },
        { name: 'production_date', label: '出产日期', type: 'date', required: true },
        { name: 'producer', label: '生产单位', type: 'text', required: true },
        { name: 'season', label: '出产季节', type: 'select', options: ['春季', '夏季', '秋季', '冬季', '全年'], required: true },
        { name: 'description', label: '描述', type: 'textarea' }
      ],
      ingredients: [
        { name: 'photo', label: '图片', type: 'photo' },
        { name: 'name', label: '名称', type: 'text', required: true },
        { name: 'category', label: '分类', type: 'select', options: [
  '主食-米面五谷', '蔬菜-叶瓜果', '蔬菜-根茎菌', '肉食-畜', '肉食-禽', '水产品-淡水', '水产品-海产', '水果', '干货-山珍海味', '腌漬食品', '奶制品', '酒类', '饮料', '调料', '熟食', '包装方便食材', '珍稀食材'
], required: true },
        { name: 'origin', label: '产地', type: 'text', required: true },
        { name: 'production_date', label: '出产日期', type: 'date', required: true },
        { name: 'producer', label: '生产单位', type: 'text', required: true },
        { name: 'price', label: '价格', type: 'text', required: true },
        { name: 'supplier', label: '供货商', type: 'text', required: true },
        { name: 'description', label: '介绍', type: 'textarea' }
      ],
      products: [
        { name: 'photo', label: '图片', type: 'photo' },
        { name: 'name', label: '名称', type: 'text', required: true },
        { name: 'origin', label: '产地', type: 'text', required: true },
        { name: 'production_date', label: '出产日期', type: 'date', required: true },
        { name: 'producer', label: '生产单位', type: 'text', required: true },
        { name: 'price', label: '价格', type: 'text', required: true },
        { name: 'supplier', label: '供货商', type: 'text', required: true },
        { name: 'main_ingredient', label: '主要成分', type: 'text' },
        { name: 'description', label: '介绍', type: 'text' },
        { name: 'method', label: '制作方法', type: 'text' },
        { name: 'effect', label: '功效', type: 'text' },
        { name: 'relation', label: '关联食谱', type: 'text' }
      ]
    };

    function showEditDataModal(tableName, rowData) {
        const modal = document.getElementById('editDataModal');
        const content = document.getElementById('editDataModalContent');
        const fields = formFieldConfig[tableName];
        let html = `<h3 style='margin-bottom:18px;'>编辑数据</h3>`;
        html += `<form id='editDataForm'>`;
        fields.forEach(f => {
            if (f.type === 'photo') {
                html += `<div class='form-group'><label>${f.label}：</label><input type='file' name='${f.name}' accept='image/*'></div>`;
                if (rowData[f.name]) {
                    html += `<div style='margin-bottom:8px;'><img src='http://localhost:3000/uploads/${rowData[f.name]}' alt='图片' style='max-width:80px;max-height:80px;border-radius:6px;'></div>`;
                }
            } else if (f.type === 'textarea') {
                html += `<div class='form-group'><label>${f.label}：</label><textarea name='${f.name}' style='width:100%'>${rowData[f.name] !== undefined ? rowData[f.name] : ''}</textarea></div>`;
            } else if (f.type === 'date') {
                html += `<div class='form-group'><label>${f.label}：</label><input type='date' name='${f.name}' value='${formatDateInput(rowData[f.name])}' style='width:100%'></div>`;
            } else if (f.type === 'select') {
                html += `<div class='form-group'><label>${f.label}：</label><select name='${f.name}' style='width:100%'>`;
                f.options.forEach(opt => {
                    html += `<option value='${opt}'${rowData[f.name] === opt ? ' selected' : ''}>${opt}</option>`;
                });
                html += `</select></div>`;
            } else {
                html += `<div class='form-group'><label>${f.label}：</label><input type='text' name='${f.name}' value='${rowData[f.name] !== undefined ? rowData[f.name] : ''}' style='width:100%'></div>`;
            }
        });
        html += `<div style='display:flex;justify-content:flex-end;gap:16px;margin-top:18px;'>
      <button type='submit' class='btn btn-primary' style='width:120px;'>保存</button>
      <button type='button' class='btn btn-secondary' id='cancelEditDataBtn' style='width:120px;'>取消</button>
    </div>`;
        html += `</form>`;
        content.innerHTML = html;
        modal.style.display = 'flex';
        // 关闭弹窗
        document.getElementById('cancelEditDataBtn').onclick = function() {
            modal.style.display = 'none';
        };
        modal.onclick = function(e) {
            if (e.target === modal) modal.style.display = 'none';
        };
        // 表单提交
        document.getElementById('editDataForm').onsubmit = async function(e) {
            e.preventDefault();
            const form = e.target;
            const formData = new FormData(form);
            // 保留原有photo
            if (!formData.get('photo')) formData.set('photo', rowData['photo'] || '');
            // 组装数据
            const updateData = {};
            fields.forEach(f => {
                if (f.name === 'photo') return;
                updateData[f.name] = formData.get(f.name);
            });
            // 处理图片上传
            let photoFile = formData.get('photo');
            let photoFilename = rowData['photo'] || '';
            if (photoFile && photoFile instanceof File && photoFile.size > 0) {
                const uploadRes = await fetch('/api/upload', {
                    method: 'POST',
                    body: (() => { const fd = new FormData(); fd.append('file', photoFile); return fd; })()
                });
                const uploadJson = await uploadRes.json();
                if (uploadJson.filename) photoFilename = uploadJson.filename;
            }
            updateData['photo'] = photoFilename;
            // 提交到后端
            const res = await fetch(`/api/${tableName}/${rowData.id}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': sessionStorage.getItem('token') || ''
                },
                body: JSON.stringify(updateData)
            });
            if (!res.ok) {
                showCenterModal('保存失败');
                return;
            }
            modal.style.display = 'none';
            // 刷新表格
            const data = await fetchTableData(tableName);
            currentTableData = data;
            renderTableData(tableName, data);
            showSuccessToast('保存成功！');
        };
    }
});

// 全局函数供HTML调用
window.backupTable = function(tableName) {
    // 仅支持系统表格 foods/ingredients/products
    const systemTables = ['foods', 'ingredients', 'products'];
    if (systemTables.includes(tableName)) {
        let defaultName = `${tableName}_${new Date().toISOString().slice(0,10)}.xlsx`;
        showCenterPrompt('请输入导出文件名（含.xlsx后缀）：', defaultName, function(filename) {
            if (!filename) return;
            if (!filename.endsWith('.xlsx')) filename += '.xlsx';
            const token = sessionStorage.getItem('token') || '';
            fetch(`http://localhost:3000/api/backup/${tableName}?filename=${encodeURIComponent(filename)}`, {
                method: 'GET',
                headers: { 'Authorization': token }
            })
            .then(response => {
                if (!response.ok) throw new Error('备份失败');
                return response.blob();
            })
            .then(blob => {
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = filename;
                document.body.appendChild(a);
                a.click();
                a.remove();
                window.URL.revokeObjectURL(url);
            })
            .catch(() => {
                showCenterModal('备份失败，您可能没有权限或服务器异常');
            });
        });
    } else {
        // 其它自定义表格的备份逻辑（如有）
        showCenterModal('暂不支持自定义表格备份');
    }
};

function deleteTable(tableName) {
    // 实现删除功能
    console.log('删除表格:', tableName);
} 

// 自定义表格备份按钮弹窗
window.customTableBackupNotSupport = function() {
    showCenterModal('自定义表格备份功能暂不支持');
};
// 修复enterCustomTable字段类型异常、字段名空格、字段为null等
window.enterCustomTable = function(tableId) {
    const modal = document.getElementById('customTableModal');
    const modalContent = document.getElementById('customTableModalContent');
    if (modal) modal.style.display = 'flex';
    if (modalContent) modalContent.innerHTML = '<div style="text-align:center;">加载中...</div>';
    fetch(`http://localhost:3000/api/custom-tables/${tableId}`, {
        headers: { 'Authorization': sessionStorage.getItem('token') || '' }
    })
    .then(res => {
        if (res.status === 404) throw new Error('notfound');
        return res.json();
    })
    .then(table => {
        // 字段安全处理
        let fields = Array.isArray(table.fields) ? table.fields : [];
        fields = fields.filter(f => f && f.name && typeof f.name === 'string');
        // 渲染表单
        let formHtml = `<span class="modal-close" onclick="closeCustomTableModal()">&times;</span>`;
        formHtml += `<h3 style="margin-bottom:12px;">${table.name} <small style="font-weight:normal;">${table.description||''}</small></h3>`;
        formHtml += `<form id="customTableDataForm" style="margin-bottom:18px;">`;
        fields.forEach(field => {
            // 字段类型安全处理
            let type = (field.type||'text').toLowerCase();
            let inputHtml = '';
            if (type === 'number') {
                inputHtml = `<input type="number" name="${field.name}" placeholder="${field.constraint||''}" class="form-control" required>`;
            } else if (type === 'date') {
                inputHtml = `<input type="date" name="${field.name}" placeholder="${field.constraint||''}" class="form-control" required>`;
            } else if (type === 'select' && field.options) {
                inputHtml = `<select name="${field.name}" class="form-control">` +
                    field.options.map(opt => `<option value="${opt}">${opt}</option>`).join('') +
                    `</select>`;
            } else if (type === 'textarea') {
                inputHtml = `<textarea name="${field.name}" placeholder="${field.constraint||''}" class="form-control" required></textarea>`;
            } else {
                inputHtml = `<input type="text" name="${field.name}" placeholder="${field.constraint||''}" class="form-control" required>`;
            }
            formHtml += `<div class="form-group">
                <label>${field.name.replace(/\s+/g, '')}：</label>
                ${inputHtml}
            </div>`;
        });
        formHtml += `<button type="submit" class="btn btn-primary">提交数据</button>`;
        formHtml += `</form>`;
        formHtml += `<div id="customTableDataList"><div style="text-align:center;">数据加载中...</div></div>`;
        if (modalContent) modalContent.innerHTML = formHtml;
        // 绑定表单提交
        const customTableDataForm = document.getElementById('customTableDataForm');
        if (customTableDataForm) {
            customTableDataForm.onsubmit = function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            const data = {};
            fields.forEach(field => {
                data[field.name] = formData.get(field.name);
            });
            fetch(`http://localhost:3000/api/custom-tables/${tableId}/data`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': sessionStorage.getItem('token') || ''
                },
                body: JSON.stringify({ data })
            })
            .then(res => res.json())
            .then(resp => {
                if (resp.message === '写入成功') {
                    loadCustomTableDataList(tableId, fields);
                    this.reset();
                } else {
                    showCenterModal(resp.error || '提交失败');
                }
            });
        };
        }
        // 加载数据列表
        loadCustomTableDataList(tableId, fields);
    })
    .catch(err => {
        if (err.message === 'notfound') {
            if (modalContent) modalContent.innerHTML = '<div style="text-align:center;color:#c00;padding:32px 0;">该表已被删除，请刷新页面。</div>';
        } else {
            if (modalContent) modalContent.innerHTML = '<div style="text-align:center;color:#c00;padding:32px 0;">加载失败，请稍后重试。</div>';
        }
    });
};

// 删除自定义表格
window.deleteCustomTable = function(event, tableId) {
    event.stopPropagation();
    showCenterConfirm('确定要删除该自定义表格及其所有数据吗？', async function(ok) {
        if (ok) {
            fetch(`http://localhost:3000/api/custom-tables/${tableId}`, {
                method: 'DELETE',
                headers: { 'Authorization': sessionStorage.getItem('token') || '' }
            })
            .then(res => {
                // 无论返回什么都刷新
                if (typeof closeCustomTableModal === 'function') closeCustomTableModal();
                if (typeof loadTablesList === 'function') loadTablesList();
                if (res.ok) return;
                res.json().then(data => {
                    if (res.status !== 404) {
                        showCenterModal((data && data.error) || '删除失败');
                    }
                }).catch(() => {
                    if (res.status !== 404) {
                        showCenterModal('删除失败，您可能没有权限或服务器异常');
                    }
                });
            })
            .catch(() => {
                showCenterModal('删除失败，您可能没有权限或服务器异常');
            });
        }
    });
}; 

window.closeCustomTableModal = function() {
    const customTableModal = document.getElementById('customTableModal');
    if (customTableModal) customTableModal.style.display = 'none';
}; 

// 加载并展示自定义表格数据
function loadCustomTableDataList(tableId, fields) {
    const dataListDiv = document.getElementById('customTableDataList');
    if (!dataListDiv) return;
    dataListDiv.innerHTML = '<div style="text-align:center;">数据加载中...</div>';
    fetch(`http://localhost:3000/api/custom-tables/${tableId}/data`, {
        headers: { 'Authorization': sessionStorage.getItem('token') || '' }
    })
    .then(res => res.json())
    .then(dataArr => {
        if (!Array.isArray(dataArr) || dataArr.length === 0) {
            dataListDiv.innerHTML = '<div style="text-align:center;color:#888;padding:18px 0;">暂无数据</div>';
            return;
        }
        let html = '<table class="custom-table-data"><thead><tr>';
        fields.forEach(f => {
            html += `<th>${f.name}</th>`;
        });
        html += '<th>操作</th></tr></thead><tbody>';
        dataArr.forEach(row => {
            html += '<tr>';
            fields.forEach(f => {
                let val = row.data && row.data[f.name] !== undefined ? row.data[f.name] : '';
                html += `<td>${val}</td>`;
            });
            html += `<td><button class="btn btn-danger btn-sm" onclick="deleteCustomTableRow(${tableId},${row.id})">删除</button></td>`;
            html += '</tr>';
        });
        html += '</tbody></table>';
        dataListDiv.innerHTML = html;
    })
    .catch(() => {
        if (dataListDiv) dataListDiv.innerHTML = '<div style="text-align:center;color:#c00;padding:18px 0;">数据加载失败</div>';
    });
}
// 删除自定义表格单行数据
window.deleteCustomTableRow = function(tableId, rowId) {
    showCenterConfirm('确定要删除该数据行吗？', async function(ok) {
        if (ok) {
            fetch(`http://localhost:3000/api/custom-tables/${tableId}/data/${rowId}`, {
                method: 'DELETE',
                headers: { 'Authorization': sessionStorage.getItem('token') || '' }
            })
            .then(res => {
                if (res.ok) {
                    loadCustomTableDataList(tableId, []);
                } else {
                    showCenterModal('删除失败');
                }
            })
            .catch(() => showCenterModal('删除失败'));
        }
    });
}; 

document.getElementById('selectAllBtn')?.addEventListener('click', function() {
    const container = document.getElementById('tableDataContainer');
    const checkboxes = container ? container.querySelectorAll('.rowCheckbox') : [];
    const allChecked = Array.from(checkboxes).every(cb => cb.checked);
    checkboxes.forEach(cb => { cb.checked = !allChecked; });
    // 切换按钮文案
    this.textContent = allChecked ? '全选' : '取消全选';
});
// 每次渲染表格后自动更新全选按钮文案
function updateSelectAllBtn() {
    const btn = document.getElementById('selectAllBtn');
    const container = document.getElementById('tableDataContainer');
    const checkboxes = container ? container.querySelectorAll('.rowCheckbox') : [];
    if (!btn) return;
    if (checkboxes.length === 0) {
        btn.textContent = '全选';
        btn.disabled = true;
    } else {
        btn.disabled = false;
        const allChecked = Array.from(checkboxes).every(cb => cb.checked);
        btn.textContent = allChecked ? '取消全选' : '全选';
    }
} 

// 绿色主题提示弹窗函数
function showSuccessToast(msg) {
    let toast = document.getElementById('successToast');
    if (!toast) {
        toast = document.createElement('div');
        toast.id = 'successToast';
        toast.style.position = 'fixed';
        toast.style.top = '60px';
        toast.style.left = '50%';
        toast.style.transform = 'translateX(-50%)';
        toast.style.background = '#43d477';
        toast.style.color = '#fff';
        toast.style.fontSize = '1.1em';
        toast.style.fontWeight = 'bold';
        toast.style.padding = '14px 36px';
        toast.style.borderRadius = '10px';
        toast.style.boxShadow = '0 2px 12px rgba(60,180,100,0.10)';
        toast.style.zIndex = 9999;
        toast.style.transition = 'opacity 0.3s';
        document.body.appendChild(toast);
    }
    toast.textContent = msg;
    toast.style.opacity = '1';
    toast.style.display = 'block';
    setTimeout(() => {
        toast.style.opacity = '0';
        setTimeout(() => { toast.style.display = 'none'; }, 300);
    }, 3000);
} 

// 屏幕中心输入弹窗
function showCenterPrompt(message, defaultValue, callback) {
    let modal = document.createElement('div');
    modal.style.position = 'fixed';
    modal.style.left = '0';
    modal.style.top = '0';
    modal.style.width = '100vw';
    modal.style.height = '100vh';
    modal.style.background = 'rgba(0,0,0,0.18)';
    modal.style.display = 'flex';
    modal.style.alignItems = 'center';
    modal.style.justifyContent = 'center';
    modal.style.zIndex = '9999';
    modal.innerHTML = `<div style=\"background:#fff;border-radius:12px;box-shadow:0 4px 24px #0002;padding:32px 36px;min-width:340px;text-align:center;\">
        <div style='font-size:20px;font-weight:600;margin-bottom:12px;color:#388e3c;'>提示</div>
        <div style='font-size:16px;margin-bottom:18px;'>${message}</div>
        <input id='centerPromptInput' style='width:90%;font-size:16px;padding:8px 6px;margin-bottom:24px;border:1.5px solid #4caf50;border-radius:5px;' value="${defaultValue || ''}" />
        <div style='margin-top:8px;'>
            <button id='centerPromptOk' style='background:#4caf50;color:#fff;border:none;border-radius:6px;padding:8px 32px;font-size:16px;cursor:pointer;margin-right:16px;'>确定</button>
            <button id='centerPromptCancel' style='background:#eee;color:#444;border:none;border-radius:6px;padding:8px 32px;font-size:16px;cursor:pointer;'>取消</button>
        </div>
    </div>`;
    document.body.appendChild(modal);
    const input = document.getElementById('centerPromptInput');
    input.focus();
    document.getElementById('centerPromptOk').onclick = function() {
        const val = input.value;
        document.body.removeChild(modal);
        if (callback) callback(val);
    };
    document.getElementById('centerPromptCancel').onclick = function() {
        document.body.removeChild(modal);
        if (callback) callback(null);
    };
    input.onkeydown = function(e) {
        if (e.key === 'Enter') document.getElementById('centerPromptOk').click();
        if (e.key === 'Escape') document.getElementById('centerPromptCancel').click();
    };
} 

// 屏幕中心确认弹窗
function showCenterConfirm(message, callback) {
    let modal = document.createElement('div');
    modal.style.position = 'fixed';
    modal.style.left = '0';
    modal.style.top = '0';
    modal.style.width = '100vw';
    modal.style.height = '100vh';
    modal.style.background = 'rgba(0,0,0,0.18)';
    modal.style.display = 'flex';
    modal.style.alignItems = 'center';
    modal.style.justifyContent = 'center';
    modal.style.zIndex = '9999';
    modal.innerHTML = `<div style=\"background:#fff;border-radius:12px;box-shadow:0 4px 24px #0002;padding:32px 36px;min-width:340px;text-align:center;\">
        <div style='font-size:20px;font-weight:600;margin-bottom:12px;color:#388e3c;'>提示</div>
        <div style='font-size:16px;margin-bottom:24px;'>${message}</div>
        <button id='centerConfirmOk' style='background:#4caf50;color:#fff;border:none;border-radius:6px;padding:8px 32px;font-size:16px;cursor:pointer;margin-right:16px;'>确定</button>
        <button id='centerConfirmCancel' style='background:#eee;color:#444;border:none;border-radius:6px;padding:8px 32px;font-size:16px;cursor:pointer;'>取消</button>
    </div>`;
    document.body.appendChild(modal);
    document.getElementById('centerConfirmOk').onclick = function() {
        document.body.removeChild(modal);
        if (callback) callback(true);
    };
    document.getElementById('centerConfirmCancel').onclick = function() {
        document.body.removeChild(modal);
        if (callback) callback(false);
    };
} 

// 绿色主题的屏幕中心弹窗
function showCenterModal(message, callback) {
    let modal = document.createElement('div');
    modal.style.position = 'fixed';
    modal.style.left = '0';
    modal.style.top = '0';
    modal.style.width = '100vw';
    modal.style.height = '100vh';
    modal.style.background = 'rgba(0,0,0,0.18)';
    modal.style.display = 'flex';
    modal.style.alignItems = 'center';
    modal.style.justifyContent = 'center';
    modal.style.zIndex = '9999';
    modal.innerHTML = `<div style="background:#fff;border-radius:12px;box-shadow:0 4px 24px #388e3c22;padding:32px 36px;min-width:320px;text-align:center;">
        <div style='font-size:20px;font-weight:600;margin-bottom:12px;color:#388e3c;'>提示</div>
        <div style='font-size:16px;margin-bottom:24px;'>${message}</div>
        <button id='centerModalBtn' style='background:#4caf50;color:#fff;border:none;border-radius:6px;padding:8px 32px;font-size:16px;cursor:pointer;'>确定</button>
    </div>`;
    document.body.appendChild(modal);
    document.getElementById('centerModalBtn').onclick = function() {
        document.body.removeChild(modal);
        if (callback) callback();
    };
} 